<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>数据源管理</title>
    <meta name="renderer" content="webkit|ie-comp|ie-stand">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <meta http-equiv="Cache-Control" content="no-siteapp"/>
    <script src="/style/public/publicStyle.js"></script>
    <style type="text/css">
        .layui-table-tool-panel li .layui-form-checkbox[lay-skin=primary] {
            /* width: 100%; */
            padding-left: 28px;
        }

        、
        .layui-table-tool-panel li {
            line-height: 30px;
            -webkit-transition: .5s all;
            transition: .5s all;
            padding-left: 10px;
            padding-right: 47px;
        }

        td .layui-form-select {
            margin-top: -10px;
            margin-left: -15px;
            margin-right: -15px;
        }

        .layui-table-cell {
            overflow: visible !important;
        }

        .layui-table-view .layui-table th {
            overflow: hidden;
        }

        .layui-table-click {
            background-color: #def0f5;
        }
    </style>
</head>

<body>
<div class="weadmin-nav">
			<span class="layui-breadcrumb" style="visibility: visible;">
			<a href="">任务管理</a><span lay-separator="">/</span>
			<a>
				<cite>任务配置</cite></a>
			</span>
    <a class="layui-btn layui-btn-sm" style="line-height:1.6em;margin-top:3px;float:right"
       href="javascript:location.replace(location.href);" title="刷新">
        <i class="layui-icon" style="line-height:30px">ဂ</i></a>
</div>

<!--表格-->
<div class="weadmin-body">
    <div class="layui-row">
        <table class="layui-hide" id="tableDataList" lay-filter="mainTableFilter"></table>
    </div>
    <div class="layui-tab">
        <ul class="layui-tab-title">
            <li class="layui-this">SQL详情</li>
        </ul>
        <div class="layui-tab-content">
            <div class="layui-tab-item layui-show">
                <div class="layui-row">
                    <div class="layui-col-md4">
                        <input type="hidden" id="outIdBase"/>
                        <textarea id="outSql" placeholder="sql内容" readonly="readonly" rows="15"
                                  class="layui-textarea"></textarea>
                    </div>
                    <div class="layui-col-md8" style="margin-top: -10px">
                        <table class="layui-hide" id="fileTable" lay-filter="fileTable"></table>
                    </div>
                </div>
            </div>
        </div>
    </div>

</div>

<script type="text/html" id="standField">
    <select name="euType" lay-filter="euType">
        <option value="STRING">字符串</option>
        <option value="NUMBER">数值型</option>
        <option value="BYTE">二进制</option>
        <option value="DATE">日期</option>
        <option value="TIMESTAMP">时间戳</option>
    </select>
</script>
<!--表格操作-->
<script type="text/html" id="op">
    <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="edit">编辑</a>
    <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="delete">删除</a>
</script>

<!--表格操作-->
<script type="text/html" id="fieldOp">
    <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="remove">删除</a>
</script>
<script type="text/html" id="toolbarDemo">
    <input class="text" style="height:35px;width:257px;" name="" id="hiddenFilter" placeholder="根据表名过滤"/>
    <button class="layui-btn layui-btn-sm" lay-event="getCheckData">新增</button>
</script>

<script type="text/html" id="filedtoolbarDemo">
    <div class="layui-btn-container" id="filedtoolbarDiv">
        <button class="layui-btn layui-btn-sm" lay-event="addRapid">快速生成</button>
        <button class="layui-btn layui-btn-sm" lay-event="editField">编辑</button>
    </div>
</script>

<div class="layui-row" id="tableForm" style="display:none;">
    <div class="layui-col-md10">
        <form class="layui-form layui-from-pane" id="formId" style="margin-top:20px" lay-filter="tableForm">
            <input type="hidden" name="idBase"/>
            <div class="layui-form-item">
                <div class="layui-row">
                    <div class="layui-col-md6">
                        <label class="layui-form-label">任务名称</label>
                        <div class="layui-input-block">
                            <input class="layui-input" name="baseName" id="jobName"/>
                        </div>
                    </div>
                    <div class="layui-col-md6">
                        <label class="layui-form-label">任务分类</label>
                        <div class="layui-input-block">
                            <select name="sdJbcls" lay-filter="sdJbcls" required nextId="naJbcls" id="sdJbcls">
                                <option value="1">hosToOds</option>
                                <option value="2">odsToDw</option>
                                <option value="3">minToDm</option>
                            </select>
                            <input type="hidden" name="naJbcls" id="naJbcls"/>
                        </div>
                    </div>
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-row">

                    <div class="layui-col-md6">
                        <label class="layui-form-label">自动建表</label>
                        <div class="layui-input-block">
                            <select name="fgCreAuto" lay-filter="fgCreAuto" required>
                                <option value="0">否</option>
                                <option value="1">是</option>
                            </select>
                        </div>
                    </div>
                    <div class="layui-col-md6">
                        <label class="layui-form-label">状态</label>
                        <div class="layui-input-block">
                            <select name="status" lay-filter="status" required>
                                <option value="0">无效</option>
                                <option value="1">有效</option>
                            </select>
                        </div>
                    </div>
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-row">
                    <div class="layui-col-md6">
                        <label class="layui-form-label">数据源</label>
                        <div class="layui-input-block">
                            <select name="idDbSou" lay-filter="idDbSouidDbSou" required id="idDbSou"
                                    nextId="naDbSou"></select>
                            <input type="hidden" name="naDbSou" id="naDbSou"/>
                        </div>
                    </div>
                    <div class="layui-col-md6">
                        <label class="layui-form-label">任务</label>
                        <div class="layui-input-block">
                            <select name="idJb" lay-filter="idJb" id="idJb"></select>
                        </div>
                    </div>
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-row">
                    <div class="layui-col-md9">
                        <label class="layui-form-label">SQL</label>
                        <div class="layui-input-block">
                            <textarea id="qsql" name="qsql" placeholder="请输入内容" required rows="15"
                                      class="layui-textarea"></textarea>
                        </div>
                    </div>

                    <div class="layui-col-md3">
                        <input type="text" name="tbNa" id="tbNa" autocomplete="off"
                               placeholder="请输入表名称" class="layui-input">
                        <table id="tables" lay-filter="tables"></table>
                    </div>
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-row">
                    <div class="layui-col-md12">
                        <label class="layui-form-label">删除sql</label>
                        <div class="layui-input-block">
                            <textarea id="del" name="del" placeholder="请输入内容" required rows="3"
                                      class="layui-textarea"></textarea>
                        </div>
                    </div>
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-row">
                    <div class="layui-col-md6">
                        <label class="layui-form-label">目标数据源</label>
                        <div class="layui-input-block">
                            <select name="idDbTar" lay-filter="idDbTar" required id="idDbTar" nextId="naDbTar"></select>
                            <input type="hidden" name="naDbTar" id="naDbTar"/>
                        </div>
                    </div>
                    <div class="layui-col-md6">
                        <label class="layui-form-label">目标表</label>
                        <div class="layui-input-block">
                            <input type="text" name="tbTar" required lay-verify="required" autocomplete="off"
                                   placeholder="请输入目标表" class="layui-input">
                        </div>
                    </div>
                </div>
            </div>

            <div class="layui-form-item" style="margin-top:40px">
                <div class="layui-input-block">
                    <button class="layui-btn  layui-btn-submit " lay-submit="" lay-filter="demo11">保存</button>
                    <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                </div>
            </div>
        </form>
    </div>
</div>

</body>

<script>
    layui.use(['util', 'laydate', 'laypage', 'layer', 'table', 'carousel', 'upload', 'element'], function () {
        var util = layui.util;
        var laydate = layui.laydate //日期
            , laypage = layui.laypage //分页
            , layer = layui.layer //弹层
            , table = layui.table //表格
            , carousel = layui.carousel //轮播
            , upload = layui.upload //上传
            , element = layui.element //元素操作
            , form = layui.form;
        var logintoken = null;
        getSharreTieba_LoginToken();
        table.render({
            elem: '#tableDataList'
            , even: false //开启隔行背景
            , cellMinWidth: 80
            , toolbar: '#toolbarDemo'
            , defaultToolbar: []
            , url: global_visit_url_prefix + '/etl/etlBase/findByPage'
            , cols: [[
                , {field: 'idBase', title: 'ID', hide: true}
                , {field: 'qsql', title: 'qsql', hide: true}
                , {field: 'baseName', title: '名称'}
                , {field: 'sdJbcls', title: '任务分类', hide: true}
                , {field: 'naJbcls', title: '任务分类名称'}
                , {field: 'fgCreAuto', title: '自动建表',templet: function(d){return d.fgCreAuto == "1" ? "是" : "否";}}
                , {field: 'status', title: '状态',templet:function(d){return d.status == "1" ? "有效" : "无效";}}
                , {field: 'idJb', title: '任务'}
                , {field: 'idDbSou', title: '数据源', hide: true}
                , {field: 'naDbSou', title: '数据源'}
                , {field: 'idDbTar', title: '目标数据源', hide: true}
                , {field: 'naDbTar', title: '目标数据源'}
                , {field: 'tbTar', title: '目标表'}
                , {fixed: 'right', title: '操作', align: 'center', toolbar: '#op'}
            ]]
            , page: true
        });

        $("body").on("keypress", "#hiddenFilter", function (event) {
            var content = $(this).val();
            if (event.keyCode == '13') {
                //执行重载
                table.reload('tableDataList', {
                    page: {
                        curr: 1 //重新从第 1 页开始
                    }
                    , where: {
                        filter: content		//在表格中进行搜索
                    }
                });
                $("#hiddenFilter").val(content);
            }
        });

        table.render({
            elem: '#fileTable'
            , even: true //开启隔行背景
            // , cellMinWidth: 80
            , toolbar: '#filedtoolbarDemo'
            // , defaultToolbar: []
            // , height: 315
            //,url:'/etl/etlBaseField/find'
            , cols: [[
                , {field: 'idFld', title: 'ID', hide: true}
                , {field: 'idBase', title: 'idBase', hide: true}
                , {field: 'field', title: '字段名', edit: 'text'}
                , {field: 'euType', title: '字段类型', templet: '#standField'}
                , {field: 'numLength', title: '长度', edit: 'text'}
                , {field: 'numPrec', title: '精度', edit: 'text'}
                , {field: 'des', title: '描述', edit: 'text'}
                , {fixed: 'right', title: '操作', align: 'center', toolbar: '#fieldOp'}
            ]]
            , done: function (res, curr, count) {
                $(".layui-table-body, .layui-table-box, .layui-table-cell").css('overflow', 'visible');
                layui.each($("select[name='euType']"), function (index, item) {
                    var elem = $(item);
                    elem.val(layui.table.cache.fileTable[index].euType);
                });
                form.render('select');

            }
            , limit: 500
            , page: false
        });
        table.reload("fileTable", {data: []});


//监听行工具事件
        table.on('tool()', function (obj) { //注：tool 是工具条事件名，mainTableFilter 是 table 原始容器的属性 lay-filter="对应的值"
            var data = obj.data //获得当前行数据
                , layEvent = obj.event; //获得 lay-event 对应的值
            if (layEvent == 'edit') {

                layer.open({
                    //layer提供了5种层类型。可传入的值有：0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层）
                    type: 1,
                    title: "编辑数据源",
                    area: ['920px', '900px'],
                    content: $("#tableForm")//引用的弹出层的页面层的方式加载修改界面表单

                });
                //动态向表传递赋值可以参看文章进行修改界面的更新前数据的显示，当然也是异步请求的要数据的修改数据的获取
                setFormValue(obj, data);
                getTables(data.idDbSou)
            } else if (layEvent == 'delete') {
                debugger
                layer.confirm('确定要删除 ' + data.baseName + ' 吗？', {
                    btn: ['确定', '取消'], //按钮
                }, function () {
                    layer.closeAll('dialog');
                    $.ajax({
                        type: "get",
                        url: "/etl/etlBase/delete",
                        async: true,
                        data: {'idBase': data.idBase},
                        success: function (json) {
                            table.reload("tableDataList");
                        }
                    });
                });
            } else if (layEvent == 'remove') {
                var layEvent = $("#filedtoolbarDiv").find(".layui-btn:first-child").attr("lay-event");
                if ("addRapid" == layEvent) {
                    return;
                }
                var oldData = table.cache["fileTable"];
                oldData.splice(obj.tr.data('index'), 1);
                table.reload('fileTable', {data: oldData});
                editFieldButton();
            }
        });

        var tableReload = function (tableId) {
            var outIdBase = $("#outIdBase").val();
            if (outIdBase != '') {
                $.ajax({
                    url: '/etl/etlBaseField/find',
                    type: 'get',
                    data: {'idBase': $("#outIdBase").val()},
                    success: function (msg) {
                        table.reload(tableId, {data: msg.data});
                    }
                })
            } else {
                table.reload(tableId, {data: []});
            }
        };
        var editFieldButton = function () {
            $("#filedtoolbarDiv").html(
                '<button class="layui-btn layui-btn-sm" lay-event="addField">新增</button>' +
                '<button class="layui-btn layui-btn-sm" lay-event="saveField">保存</button>' +
                '<<button class="layui-btn layui-btn-sm" lay-event="returnBack">返回</button>');
        };

//数据源监控
        form.on('select(idDbSouidDbSou)', function (data) {
            getTables(data.value, '');
        });

        var getTables = function (idDb, tbNa) {
            $.ajax({
                url: '/etl/baseDbInfo/getTables',
                type: 'get',
                data: {'idDb': idDb, 'tableName': tbNa},
                success: function (msg) {
                    table.render({
                        elem: '#tables'
                        , data: msg.data
                        , height: 275
                        , cols: [[
                            {field: 'tbName', title: '数据源表名称'}
                        ]]
                        , page: false
                    });

                }
            })
        }

        table.on('rowDouble(tables)', function (obj) {
            var data = obj.data;
            var idDbSou = $("#idDbSou option:selected").val();
            var oSql = document.getElementById("qsql").value;
            debugger
            $.ajax({
                url: '/etl/baseDbInfo/getTableInfo',
                type: 'get',
                data: {'idDb': idDbSou, 'tables': data.tbName},
                success: function (msg) {
                    debugger
                    var sql = 'select ';
                    $.each(msg.data, function (index, item) { //循环加入 data的元素
                        sql = sql + item.field + ',';
                    });
                    sql = sql + 'from  ' + data.tbName;
                    document.getElementById("qsql").value = oSql + '\n' + sql.replace(",from", "  from").toUpperCase();
                }
            })
        })
//内容改变出发
        $("#tbNa").on("input", function (e) {
            //获取input输入的值
            var tbNa = e.delegateTarget.value;
            var idDbSou = document.getElementById("idDbSou").value;
            getTables(idDbSou, tbNa);
        });
        //监听表头
        table.on('toolbar()', function (obj) {
            var checkStatus = table.checkStatus(obj.config.id);
            switch (obj.event) {
                case 'getCheckData':
                    layer.open({
                        //layer提供了5种层类型。可传入的值有：0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层）
                        type: 1,
                        title: "新增数据源",
                        area: ['820px', '630px'],
                        content: $("#tableForm")//引用的弹出层的页面层的方式加载修改界面表单
                    });
                    setFormValue(obj, null);
                    break;
                case 'addField':
                    var tableData = table.cache.fileTable;
                    if (tableData == null) {
                        tableData = [];
                    }
                    tableData.push({
                        "euType": "STRING"
                    });
                    table.reload("fileTable", {data: tableData});
                    editFieldButton();
                    break;
                case 'addRapid' :
                    var tableData = table.cache.fileTable;
                    if (tableData.length > 0) {
                        layer.alert("请先删除已有数据");
                        return;

                    }
                    var outIdBase = $("#outIdBase").val();
                    debugger
                    if (outIdBase != '') {
                        $.ajax({
                            url: '/etl/etlBaseField/findByAuto',
                            type: 'get',
                            data: {'idBase': outIdBase},
                            success: function (msg) {
                                table.reload("fileTable", {data: msg.data});
                                editFieldButton();
                            }
                        })
                    } else {
                        layer.alert("请先选择任务");
                    }
                    break;
                case 'saveField':
                    debugger
                    var data = obj.config.data;
                    if (data.length > 0) {
                        $.ajax({
                            url: '/etl/etlBaseField/saveList',
                            type: 'post',
                            dataType: 'json',
                            contentType: 'application/json;charset=UTF-8',
                            data: JSON.stringify(data),
                            success: function (msg) {
                                table.reload("fileTable", msg.data);
                            }
                        });
                    } else {
                        layer.alert("数据不能为空");
                    }
                    break;
                case 'editField':
                    editFieldButton();
                    break;
                case 'returnBack':
                    layer.confirm('返回会导致已变更数据的丢失，是否继续？', {
                        btn: ['继续', '取消'], //按钮
                    }, function () {
                        layer.closeAll('dialog');
                        tableReload("fileTable");
                    });
                    break;

            }
            ;
        });

        //监听行单击事件（双击事件为：rowDouble）
        table.on('row(mainTableFilter)', function (obj) {
            var data = obj.data;
            $("#outSql").val(data.qsql);
            $("#outIdBase").val(data.idBase);
            obj.tr.addClass('layui-table-click').siblings().removeClass('layui-table-click');
            tableReload("fileTable");
        });

        //监听弹出框表单提交，massage是修改界面的表单数据'submit(demo11),是修改按钮的绑定
        function setFormValue(obj, data) {
            if (data == null) {
                $("#formId")[0].reset();
            } else {
                form.val("tableForm", data);
            }
            form.on('submit(demo11)', function (massage) {
                $.ajax({
                    url: '/etl/etlBase/save',
                    type: 'post',
                    dataType: 'json',
                    contentType: 'application/json;charset=UTF-8',
                    data: JSON.stringify(massage.field),
                    success: function (msg) {
                        table.reload("tableDataList");
                    }
                })
            })


        }
    });

    layui.use('form', function () {
        var $ = layui.$;
        var form = layui.form;
        $.ajax({
            url: '/etl/baseDb/find',
            type: 'get',
            success: function (data1) {
                var data = data1.data; //提出返回数据中的data
                $("#idDbSou").empty();//清空默认值
                if (data !== null) {
                    var flag = true;
                    $.each(data, function (index, item) { //循环加入 data的元素
                        $("#idDbSou").append("<option value='" + item.idDb + "'>" + item.na + "</option>");
                        $("#idDbTar").append("<option value='" + item.idDb + "'>" + item.na + "</option>");
                        if (flag) {
                            $("#naDbSou").val(item.na);
                            $("#naDbTar").val(item.na);
                            flag = false;
                        }
                    });
                }
                ;
            }
        });
        $.ajax({
            url: '/etl/etlJb/find',
            type: 'get',
            success: function (data1) {
                var data = data1.data; //提出返回数据中的data
                $("#idJb").empty();//清空默认值
                if (data !== null) {
                    var flag = true;
                    $.each(data, function (index, item) { //循环加入 data的元素
                        $("#idJb").append("<option value='" + item.idJb + "'>" + item.na + "</option>");
                    });
                }
                ;
            }
        });
        form.render('select');
        $("#naJbcls").val($("#sdJbcls").text().trim());
        form.on('select', function (data) {
            var nextId = data.elem.attributes.nextid;
            if (nextId != null) {
                $("#" + nextId.value).val($(this).text());
            }
        });
        form.on('select(euType)', function (data) {
            debugger
            var elem = $(data.elem);
            var trElem = elem.parents('tr');
            // 更新到表格的缓存数据中，才能在获得选中行等等其他的方法中得到更新之后的值
            var tableData = layui.table.cache.fileTable;
            tableData[trElem.data('index')][elem.attr('name')] = data.value;
            form.render('select');
        })


    });
</script>

</html>